// CICP by Arkowitz

list http_list = [];
string cicp_host;
key curReq;
integer graphId = 0;
key cardKey;

processDispatchLine ( string line ) {
    //llOwnerSay(line);
    if ( line == "more" )
        curReq = llHTTPRequest(cicp_host + "type=dispatch&layer=" +
                               (string)graphId, http_list, "");
    else if ( llGetSubString(line, 0, 4) == "error" )
        llOwnerSay(line);
    else if ( line != "new" && line != "mod" ) {
        list lineList = llParseString2List(line, [";"], []);
        integer targPrimId = (integer)llList2String(lineList, 0);
        llRegionSay(targPrimId * -1, llList2String(lineList, 1));
    }
}

default {

    state_entry () {
        llOwnerSay( "CICP Start" );
    }

    touch_start ( integer total_number ) {
        cardKey = llGetNotecardLine("cicp_config", 0);
    }
    
    http_response ( key request_id, integer status, list metadata,
string body ) {
        if ( request_id != curReq )
            return;
        //llOwnerSay(body);
        list bodyList = llParseString2List(body, ["\n"], []);
        integer i;
        for ( i = 0; i < llGetListLength(bodyList); i++ ) {
            string line = llList2String(bodyList, i);
            processDispatchLine(line);
            if ( i == llGetListLength(bodyList) - 1 && line != "more" )
                llDie();
        }
    }
    
    dataserver ( key queryId, string data ) {
        if ( queryId == cardKey ) {
            cicp_host = data;
            if ( llGetSubString(cicp_host, 0, 4) == "https" )
                http_list = [HTTP_VERIFY_CERT, FALSE];
                
            vector layerPos = llGetPos();
            string msg = "init," + (string)layerPos.x + "," +
                (string)layerPos.z + "," + (string)layerPos.y;
            curReq = llHTTPRequest(cicp_host + "type=msg&msg=" + msg +
                                   "&region=" + llGetRegionName(), http_list, "");
        }
    }
}